// 附件的预览、下载
import axios from 'axios'
import bus from './bus.js'
import { imgReg } from '@/utils/validate'
// import { getToken } from "@/utils/auth"

function checkStatus(response) {
  if (response && response.status === 200) {
    // loading,如果http状态码正常，则直接返回数据
    let _data = response.data
    if (!_data) {
      bus.$message.error('服务器开了个小差')
      return false
    } else {
      // response.headers['content-type']
      const uu = 'data:' + 'image/jpeg' + ';base64,' + btoa(new Uint8Array(_data).reduce(
        (data, byte) => data + String.fromCharCode(byte),
        ''
      ))
      return uu
    }
  } else {
    return false
  }
}

export function getFileReadRIS(fileUrl) {
  let dataUrl = `${window.g.API_ROOT_RIS}/api/v1/file/read`
  // var showUrl = '';
  // 二进制流转换为base64
  return axios.get(dataUrl, {
    params: { filepath: fileUrl },
    responseType: 'arraybuffer'
  }).then(res => {
    return checkStatus(res)
  }).catch(ex => {
    return ''
  })
}

export function getFileRead(fileUrl) {
  let dataUrl = `${window.g.API_ROOT_JWT}/api/File/ReadFile`
  // var showUrl = '';
  // 二进制流转换为base64
  return axios.get(dataUrl, {
    params: { fileUrl: fileUrl },
    responseType: 'arraybuffer'
  }).then(res => {
    return checkStatus(res)
  }).catch(ex => {
    return ''
  })
}

export function getFileDownload(fileUrl) {
  let dataUrl = `${window.g.API_ROOT_JWT}/api/File/DownLoadFile`
  // var showUrl = '';
  // 二进制流转换为base64
  return axios.get(dataUrl, {
    params: { fileUrl: fileUrl },
    responseType: 'arraybuffer'
  }).then(res => {
    return checkStatus(res)
  }).catch(ex => {
    return ''
    //  console.error(ex)
  })
}

// 预览
export function winOpenFile(fileName, content) {
  if (imgReg(fileName)) {
    // 验证是否为图片
    const img = new Image()
    img.src = content
    const newWin = window.open('', '_blank')
    newWin.document.write(img.outerHTML)
    newWin.document.title = fileName
    newWin.document.close()
  } else {
    window.open(content, '_blank')
  }
}

// 下载
export function downloadFile(fileName, content) {
  var aLink = document.createElement('a')
  var blob = base64ToBlob(content) // new Blob([content]);
  var evt = document.createEvent('HTMLEvents')
  evt.initEvent('click', true, true)// initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
  aLink.download = fileName
  aLink.href = URL.createObjectURL(blob)
  // aLink.dispatchEvent(evt);
  aLink.click()
}
// base64转blob
function base64ToBlob(code) {
  var parts = code.split(';base64,')
  var contentType = parts[0].split(':')[1]
  var raw = window.atob(parts[1])
  var rawLength = raw.length

  var uInt8Array = new Uint8Array(rawLength)

  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array], { type: contentType })
}
